﻿using System;
using Loki.Commands;
using Loki.UI;
using Loki.Utils;
using Luna.Model.Crm;
using Luna.UI.Common;

namespace Luna.UI.Crm
{
    public class EntityListViewModel : Screen
    {
        public ICrmService Crm { get; set; }

        public EntityListViewModel()
        {
            DisplayName = "Annuaire";

            Entities = new BindableCollection<IEntity>();
        }

        public BindableCollection<IEntity> Entities { get; private set; }

        protected override void OnInitialize()
        {
            Commands.Handle(LunaCommands.Add, Application_Add);
            Commands.Handle(ApplicationCommands.Refresh, Application_Refresh);
            Commands.Handle(ApplicationCommands.Open, Application_Open_CanExecute, Application_Open_Execute);
            base.OnInitialize();
        }

        protected override void OnLoad()
        {
            Entities.Clear();
            Entities.AddRange(Crm.Entities);
            base.OnLoad();
        }

        private void Application_Refresh(object sender, EventArgs e)
        {
            Entities.Clear();
            Entities.AddRange(Crm.Entities);
        }

        private void Application_Open_CanExecute(object sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute |= e.Parameter is IEntity || e.Parameter is IEditableEntity;
        }

        private void Application_Open_Execute(object sender, CommandEventArgs e)
        {
            IEditableEntity reference = e.Parameter as IEditableEntity;
            if (reference == null)
            {
                var entity = e.Parameter as IEntity;
                if (entity != null)
                {
                    reference = entity.EditableCopy;
                }
            }

            if (reference != null)
            {
                var message = new NavigationMessage<EntityEditViewModel>();
                message.Initializer = x => x.Entity = reference;
                message.Selector = x => x.Entity != null && x.Entity.ID == reference.ID;
                CommonBus.PublishOnUIThread(message);
            }
        }

        private void Application_Add(object sender, EventArgs e)
        {
            var entity = Context.Get<IEditableEntity>();
            entity.Name = "Nouveau contact";
            ApplicationCommands.Open.Execute(entity);
        }
    }
}